package com.seecen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.common.BaseResponse;
import com.seecen.common.ResultUtils;
import com.seecen.exception.ErrorCode;
import com.seecen.pojo.entity.Coupon;
import com.seecen.pojo.entity.UserCoupon;
import com.seecen.service.CouponService;
import com.seecen.mapper.CouponMapper;
import com.seecen.service.UserCouponService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
* @author 小辛
* @description 针对表【allmaster_coupon(优惠券表)】的数据库操作Service实现
* @createDate 2025-10-19 14:33:19
*/
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon>
    implements CouponService{

    @Resource
    private UserCouponService userCouponService;

    @Override
    public BaseResponse<List<Coupon>> getAvailableCoupons() {
        try {
            QueryWrapper<Coupon> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1) // 启用状态
                    .le("start_time", new Date()) // 开始时间小于等于当前时间
                    .ge("end_time", new Date()) // 结束时间大于等于当前时间
                    .gt("total_count", 0) // 总数量大于0
                    .apply("received_count < total_count"); // 已领取数量小于总数量
            
            List<Coupon> coupons = this.list(queryWrapper);
            return ResultUtils.success(coupons);
        } catch (Exception e) {
            return new BaseResponse<>(ErrorCode.SYSTEM_ERROR.getCode(), null, "获取可用优惠券失败");
        }
    }

    @Override
    @Transactional
    public BaseResponse<String> claimCoupon(Integer userId, Integer couponId) {
        try {
            // 检查优惠券是否存在且可用
            Coupon coupon = this.getById(couponId);
            if (coupon == null) {
                return new BaseResponse<>(ErrorCode.NOT_FOUND_ERROR.getCode(), null, "优惠券不存在");
            }
            
            if (coupon.getStatus() != 1) {
                return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(), null, "优惠券已禁用");
            }
            
            Date now = new Date();
            if (now.before(coupon.getStartTime()) || now.after(coupon.getEndTime())) {
                return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(), null, "优惠券不在有效期内");
            }
            
            if (coupon.getReceivedCount() >= coupon.getTotalCount()) {
                return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(), null, "优惠券已被领完");
            }
            
            // 检查用户是否已经领取过
            if (userCouponService.hasUserClaimedCoupon(userId, couponId)) {
                return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(), null, "您已经领取过该优惠券");
            }
            
            // 创建用户优惠券记录
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setUserId(userId);
            userCoupon.setCouponId(couponId);
            userCoupon.setCouponCode(userCouponService.generateCouponCode());
            userCoupon.setStatus(0); // 未使用
            userCoupon.setReceiveTime(now);
            userCoupon.setCreateTime(now);
            userCoupon.setUpdateTime(now);
            
            boolean saved = userCouponService.save(userCoupon);
            if (!saved) {
                return new BaseResponse<>(ErrorCode.SYSTEM_ERROR.getCode(), null, "领取优惠券失败");
            }
            
            // 更新优惠券已领取数量
            coupon.setReceivedCount(coupon.getReceivedCount() + 1);
            coupon.setUpdateTime(now);
            this.updateById(coupon);
            
            return ResultUtils.success("领取成功");
        } catch (Exception e) {
            return new BaseResponse<>(ErrorCode.SYSTEM_ERROR.getCode(), null, "领取优惠券失败");
        }
    }

    @Override
    @Transactional
    public BaseResponse<String> claimAllCoupons(Integer userId) {
        try {
            BaseResponse<List<Coupon>> availableCouponsResponse = getAvailableCoupons();
            if (availableCouponsResponse.getCode() != 200) {
                return new BaseResponse<>(ErrorCode.SYSTEM_ERROR.getCode(), null, "获取可用优惠券失败");
            }
            
            List<Coupon> availableCoupons = availableCouponsResponse.getData();
            if (availableCoupons.isEmpty()) {
                return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(), null, "暂无可领取的优惠券");
            }
            
            int successCount = 0;
            for (Coupon coupon : availableCoupons) {
                // 检查用户是否已经领取过
                if (!userCouponService.hasUserClaimedCoupon(userId, coupon.getCouponId())) {
                    BaseResponse<String> claimResult = claimCoupon(userId, coupon.getCouponId());
                    if (claimResult.getCode() == 200) {
                        successCount++;
                    }
                }
            }
            
            if (successCount == 0) {
                return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(), null, "没有可领取的新优惠券");
            }
            
            return ResultUtils.success("成功领取 " + successCount + " 张优惠券");
        } catch (Exception e) {
            return new BaseResponse<>(ErrorCode.SYSTEM_ERROR.getCode(), null, "一键领取失败");
        }
    }
}




